﻿<template>
  <div class="app-container">
    <div class="chart-title">档案管理</div>
    <div class="chart-content">
      <div class="chart-list">
        <el-table
          :data="tableListData"
          row-key="id"
          :row-style="toggleDisplayTr"
          border
          stripe
          class="init_table"
        >
          <el-table-column
            fixed="left"
            align="center"
            width="55"
            type="index"
            label="序号"
          ></el-table-column>
          <el-table-column
            label="权限名称"
            min-width="200"
            show-overflow-tooltip
            align="left"
          >
            <template slot-scope="scope">
              <p :style="`margin-left: ${scope.row.__level * 20}px;margin-top:0;margin-bottom:0`">
                <i
                  class="permission_toggleFold"
                  :class="toggleFoldingClass(scope.row)"
                  @click="toggleFoldingStatus(scope.row)"
                ></i>
                {{ scope.row.title }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.id')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('menu.name')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('menu.pid')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.pid }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('menu.title')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.title }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('menu.weigh')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.weigh }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
import dropDownSelect from "@/views/select/dropDownSelect"; // 分页选择控件
import { getToken } from "@/utils/auth";
import Vue from "vue";
export default {
  name: "Itoc",
  components: {
    "drop-down-select": dropDownSelect
  },
  data() {
    const validateName = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 20) {
          callback(new Error("名称长度不能大于20个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)[\u4e00-\u9fff\w]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error("名称只能包含汉字、英文、“_”和数字且不为纯数字或纯符号")
            );
          }
        }
      } else {
        callback(new Error("请填写名称"));
      }
    };
    return {
      tableListData: [], // tableListData 展示数据的data
      foldList: [], // 该数组中的值 都会在列表中进行隐藏  死亡名单
      tableKey: 0,
      total: null,
      listLoading: true,
      deadlineOptions: [
        {
          value: 1,
          label: "1年"
        },
        {
          value: 2,
          label: "2年"
        },
        {
          value: 3,
          label: "3年"
        },
        {
          value: 99,
          label: "不限"
        }
      ],
      listQuery: {
        page: 1,
        limit: 20,
        name: "",
        code: "",
        status: "",
        linkname: "",
        linkname_mobile: "",
        region_name: "",
        region_type: ""
      },
      districtsOptions: [],
      LastDateTimestamp: undefined,
      mealList: [
        {
          goods_date: new Date().getTime(),
          goods_id: undefined,
          goods_name: ""
        },
        {
          goods_date: new Date().getTime() + 24 * 60 * 60 * 1000,
          goods_id: undefined,
          goods_name: ""
        },
        {
          goods_date: new Date().getTime() + 2 * (24 * 60 * 60 * 1000),
          goods_id: undefined,
          goods_name: ""
        },
        {
          goods_date: new Date().getTime() + 3 * (24 * 60 * 60 * 1000),
          goods_id: undefined,
          goods_name: ""
        },
        {
          goods_date: new Date().getTime() + 4 * (24 * 60 * 60 * 1000),
          goods_id: undefined,
          goods_name: ""
        },
        {
          goods_date: new Date().getTime() + 5 * (24 * 60 * 60 * 1000),
          goods_id: undefined,
          goods_name: ""
        },
        {
          goods_date: new Date().getTime() + 6 * (24 * 60 * 60 * 1000),
          goods_id: undefined,
          goods_name: ""
        }
      ],
      temp: {
        id: undefined,
        goods_id: undefined,
        goods_name: undefined
      },
      dialogFormVisible: false,
      dialogVisible: false,
      dialogStatus: "",
      textMap: {
        edit: "编辑",
        create: "新建排餐",
        review: "审核",
        read: "查看"
      },
      editrules: {
        name: [{ required: true, trigger: "blur", validator: validateName }]
      },
      createDisabled: true,
      updateDisabled: true,
      goodsOptions: [],
      goodsCount: undefined,
      pageSize: 20
    };
  },
  computed: {
    /** *******************************
     ** Fn: foldAllList
     ** Intro: 记录属性结构的首层节点
     ** Author: zyx
     ******************************* **/
    foldAllList() {
      return this.tableListData.map(x => x.__identity);
    }
  },
  created() {
    const token = getToken()
    if (token && !this.$store.state.socket.loginTransition && !this.$store.state.socket.loginAccount) {
      this.tokenLogin(token)
    }
    this.getList();
  },
  methods: {
    tokenLogin(token) {
      const path = {
        app: "wxadmin",
        api: "api_wxadmin_admin_keepLogin",
        version: "1.0",
        type: 2,
        data: {
          token: token
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        this.socketData(res);
      });
    },
    handleNodeClick(data) {
      console.log(data);
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleRefresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        goods_name: "",
        goods_date: ""
      };
      this.getList();
    },
    // 获取菜单列表
    getList() {
      this.listLoading = true;
      const path = {
        app: "menu",
        api: "api_menu_index_getList",
        version: "1.0",
        type: 1,
        data: {

        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    /** *******************************
     ** Fn: toggleFoldingStatus
     ** Intro: 切换展开 还是折叠
     ** @params: params 当前点击行的数据
     ** Author: zyx
     ******************************* **/
    toggleFoldingStatus(params) {
      this.foldList.includes(params.__identity)
        ? this.foldList.splice(this.foldList.indexOf(params.__identity), 1)
        : this.foldList.push(params.__identity);
    },
    /** *******************************
     ** Fn: toggleDisplayTr
     ** Intro: 该方法会对每一行数据都做判断 如果foldList 列表中的元素 也存在与当前行的 __family列表中  则该行不展示
     ** @params:
     ** Author: zyx
     ******************************* **/
    toggleDisplayTr({ row, index }) {
      for (let i = 0; i < this.foldList.length; i++) {
        const item = this.foldList[i];
        // 如果foldList中元素存在于 row.__family中，则该行隐藏。  如果该行的自身标识等于隐藏元素，则代表该元素就是折叠点
        if (row.__family.includes(item) && row.__identity !== item) {
          return "display:none;";
        }
      }
      return "";
    },
    /** *******************************
     ** Fn: toggleFoldingClass
     ** Intro: 如果子集长度为0，则不返回字体图标。
     ** Intro: 如果子集长度为不为0，根据foldList是否存在当前节点的标识返回相应的折叠或展开图标
     ** Intro: 关于class说明：permission_placeholder返回一个占位符，具体查看class
     ** @params: params 当前行的数据对象
     ** Author: zyx
     ******************************* **/
    toggleFoldingClass(params) {
      return params.childrens
        ? this.foldList.indexOf(params.__identity) === -1
          ? "iconfont icon-minus-square-o"
          : "iconfont icon-plussquareo"
        : "permission_placeholder";
    },
    /** *******************************
     ** Fn: formatConversion
     ** Intro: 将树形接口数据扁平化
     ** @params: parent 为当前累计的数组  也是最后返回的数组
     ** @params: children 为当前节点仍需继续扁平子节点的数据
     ** @params: index 默认等于0， 用于在递归中进行累计叠加 用于层级标识
     ** @params: family 装有当前包含元素自身的所有父级 身份标识
     ** @params: elderIdentity 父级的  唯一身份标识
     ** Author: zyx
     ******************************* **/
    formatConversion(
      parent,
      childrens,
      index = 0,
      family = [],
      elderIdentity = "x"
    ) {
      // children如果长度等于0，则代表已经到了最低层
      // let page = (this.startPage - 1) * 10
      if (childrens) {
        if (childrens.length > 0) {
          childrens.map((x, i) => {
            // 设置 __level 标志位 用于展示区分层级
            Vue.set(x, "__level", index);
            // 设置 __family 为家族关系 为所有父级，包含本身在内
            Vue.set(x, "__family", [...family, elderIdentity + "_" + i]);
            // 本身的唯一标识  可以理解为个人的身份证咯 一定唯一。
            Vue.set(x, "__identity", elderIdentity + "_" + i);
            parent.push(x);
            // 如果仍有子集，则进行递归
            if (x.childrens) {
              if (x.childrens.length > 0) {
                this.formatConversion(
                  parent,
                  x.childrens,
                  index + 1,
                  [...family, elderIdentity + "_" + i],
                  elderIdentity + "_" + i
                );
              }
            }
          });
        }
      }
      console.log('parent')
      return parent;
    },
    handleCreate() {
      // this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleRead(row) {
      // 打开查看弹窗
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "read";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 编辑排餐
    handleEdit(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["editForm"].clearValidate();
      });
    },
    // 添加排餐
    createData() {
      const dataList = JSON.parse(JSON.stringify(this.mealList));
      const data = [];
      dataList.forEach(element => {
        console.log("element", element);
        if (element.goods_id) {
          element.goods_date = this.timestampToTime(
            element.goods_date,
            "{y}-{m}-{d}"
          );
          data.push(element);
        }
      });

      if (this.createDisabled) {
        this.createDisabled = false;
        // const data = this.upData();
        const path = {
          app: "arrange",
          api: "api_arrange_index_add",
          version: "1.0",
          type: "1,2",
          data: data
        };
        this.socketApi.sendSock(JSON.stringify(path), res => {
          if (res) {
            this.socketData(res);
          }
          setTimeout(() => {
            this.createDisabled = true;
          }, 1000);
        });
      }
    },
    // 更新排餐
    updateData() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          if (this.updateDisabled) {
            this.updateDisabled = false;
            const data = {
              id: this.temp.id,
              goods_id: this.temp.goods_id
            };
            const path = {
              app: "arrange",
              api: "api_arrange_index_edit",
              version: "1.0",
              type: "1,2",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(path), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.updateDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    // 商品选择
    getGoods(pageNumber, search, name) {
      const path = {
        app: "goods",
        api: "api_goods_index_getList",
        version: "1.0",
        data: {
          rows: this.pageSize,
          page: pageNumber || 1,
          name: search || "",
          returnType: name || ""
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    choose(data, index, name) {
      if (name === "goods") {
        this.mealList[index].goods_id = data.id;
        this.mealList[index].goods_name = data.name;
      } else if (name === "goodsEdit") {
        this.temp.goods_id = data.id;
        this.temp.goods_name = data.name;
      }
    },
    remove(index, name) {
      if (name === "goods") {
        this.mealList[index].goods_id = undefined;
        this.mealList[index].goods_name = "";
      } else if (name === "goodsEdit") {
        this.temp.goods_id = undefined;
        this.temp.goods_name = "";
      }
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "api_wxadmin_admin_keepLogin") {
            this.$store.dispatch("loginTransition", true);
            this.socketApi.sendCache(res => {
              this.socketData(res);
            });
          } else if (resj.api === "api_menu_index_getList") {
            console.log('this.list', resj.data)
            this.total = resj.count;

            const data = JSON.parse(
              JSON.stringify(resj.data).replace(/children/g, "childrens")
            );
            this.tableListData = this.formatConversion([], data);
            this.listLoading = false;
          } else if (resj.api === "api_archives_itoc_sevenRegional") {
            this.districtsOptions = resj.data;
          } else if (
            resj.api === "api_goods_index_getList" &&
            resj.type === "getGoods"
          ) {
            this.goodsOptions = resj.data;
            this.goodsCount = resj.count;
          } else if (
            resj.api === "api_goods_index_getList" &&
            resj.type === "addGoods"
          ) {
            this.goodsOptions = this.goodsOptions.concat(resj.data);
          } else if (resj.api === "api_arrange_index_getEndTime") {
            if (resj.data.date) {
              this.LastDateTimestamp =
                new Date(resj.data.date).getTime() + 24 * 60 * 60 * 1000;
            } else {
              this.LastDateTimestamp = new Date().getTime();
            }
            for (let index = 0; index < 7; index++) {
              this.$set(
                this.mealList[index],
                "goods_date",
                this.LastDateTimestamp + index * (24 * 60 * 60 * 1000)
              );
            }
          } else if (resj.api === "api_arrange_index_add") {
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getList();
          } else if (resj.api === "api_arrange_index_edit") {
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
            this.dialogVisible = false;
            this.getList();
          }
        }
      }
    }
  }
};
</script>
<style scoped>
.permission_toggleFold {
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  display: inline-block;
  position: relative;
}
.permission_toggleFold.iconfont.icon-minus-square-o:after {
  content: "-";
  color: #9e9e9e;
  font-size: 20px;
}
.permission_toggleFold.iconfont.icon-plussquareo:after {
  content: "+";
  color: #9e9e9e;
  font-size: 20px;
}
</style>
